package com.example.bookmanagement.controller;

import com.example.bookmanagement.entity.Book;
import com.example.bookmanagement.service.BookService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    // 显示所有图书
    @GetMapping
    public String listBooks(Model model,
                            @RequestParam(required = false) String keyword,
                            @RequestParam(required = false) String success) {
        List<Book> books;

        if (keyword != null && !keyword.trim().isEmpty()) {
            books = bookService.searchByKeyword(keyword.trim());
            model.addAttribute("keyword", keyword);
        } else {
            books = bookService.getAllBooks();
        }

        model.addAttribute("books", books);
        model.addAttribute("totalBooks", bookService.getBookCount());

        if ("add".equals(success)) {
            model.addAttribute("successMessage", "图书添加成功！");
        } else if ("edit".equals(success)) {
            model.addAttribute("successMessage", "图书更新成功！");
        } else if ("delete".equals(success)) {
            model.addAttribute("successMessage", "图书删除成功！");
        }

        return "book/list";
    }

    // 显示添加图书表单
    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("book", new Book());
        return "book/add";
    }

    // 处理添加图书
    @PostMapping("/add")
    public String addBook(@Valid @ModelAttribute Book book,
                          BindingResult result,
                          Model model,
                          RedirectAttributes redirectAttributes) {

        // 检查ISBN是否已存在
        if (bookService.isIsbnExists(book.getIsbn())) {
            result.rejectValue("isbn", "error.book", "ISBN已存在");
        }

        if (result.hasErrors()) {
            return "book/add";
        }

        bookService.saveBook(book);
        redirectAttributes.addAttribute("success", "add");
        return "redirect:/books";
    }

    // 显示编辑图书表单
    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model) {
        Optional<Book> book = bookService.getBookById(id);
        if (book.isPresent()) {
            model.addAttribute("book", book.get());
            return "book/edit";
        }
        return "redirect:/books?error=not_found";
    }

    // 处理编辑图书
    @PostMapping("/edit/{id}")
    public String updateBook(@PathVariable Long id,
                             @Valid @ModelAttribute Book book,
                             BindingResult result,
                             Model model,
                             RedirectAttributes redirectAttributes) {

        // 检查ISBN是否已存在（排除当前图书）
        if (bookService.isIsbnExists(book.getIsbn(), id)) {
            result.rejectValue("isbn", "error.book", "ISBN已存在");
        }

        if (result.hasErrors()) {
            return "book/edit";
        }

        Book updatedBook = bookService.updateBook(id, book);
        if (updatedBook != null) {
            redirectAttributes.addAttribute("success", "edit");
        } else {
            redirectAttributes.addAttribute("error", "update_failed");
        }

        return "redirect:/books";
    }

    // 删除图书
    @GetMapping("/delete/{id}")
    public String deleteBook(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        if (bookService.deleteBook(id)) {
            redirectAttributes.addAttribute("success", "delete");
        } else {
            redirectAttributes.addAttribute("error", "delete_failed");
        }
        return "redirect:/books";
    }

    // 查看图书详情
    @GetMapping("/detail/{id}")
    public String viewBookDetail(@PathVariable Long id, Model model) {
        Optional<Book> book = bookService.getBookById(id);
        if (book.isPresent()) {
            model.addAttribute("book", book.get());
            return "book/detail";
        }
        return "redirect:/books?error=not_found";
    }
}